////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.more;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;
import cc.telecomdigital.tdstock.adapter.StockANalysisViewHolder;
import cc.telecomdigital.tdstock.adapter.StockAnalysisListItemAdapter;

/**
 * 
 * @author haibo
 * 
 *  for  list item on stock analysis
 *
 */
public class StockAnalysisContentActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String	TAG			= StockAnalysisContentActivity.class.getSimpleName();
	private static final long		START_ID	= 90000l;

	private ListView						_listView;
	private Button							_toolBtnReturn;
	private TextView						_topBarTitle;
	private ViewGroup						_listViewHeader;

	private static StockAnalysisListItemAdapter	_twoColumnAdapter;
	private static List<StockANalysisViewHolder>	_twoColumnList;

	private SharedPreferences				_prefsStockCode;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_stock_analysis_content);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(), StockAnalysisActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(StockAnalysisActivity.class, intent);
			}
		});

		_messageHandler = null; //this activity no need it.
		_topBarTitle = (TextView) findViewById(R.id.topbar_title);
		_listViewHeader = (ViewGroup) findViewById(R.id.transparent_panel);
		_listView = (ListView) findViewById(R.id.stock_analysis_list);

		_twoColumnList = new ArrayList<StockANalysisViewHolder>();
		_twoColumnAdapter = new StockAnalysisListItemAdapter(LayoutInflater.from(this), _twoColumnList);

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				//the first line is the title
				if (position != -1 && _twoColumnList.size() >= position + 1)
				{
					try
					{
						StringBuffer stkCode = new StringBuffer();
						String itemName = _twoColumnList.get(position).item_name
								.trim();
						for (int index = 0; index < 5; index++)
						{
							if (itemName.charAt(index) >= '0'
									&& itemName.charAt(index) <= '9')
								stkCode.append(itemName.charAt(index));
							else
								break;
						}

						_prefsStockCode = getSharedPreferences(
								CommonDefn.SYSTEM_CURRENT_SETTING,
								Context.MODE_PRIVATE);
						_prefsStockCode.edit().putString(
								CommonDefn.PREFERENCE_STOCK_CODE,
								String.valueOf(Integer.parseInt(stkCode
										.toString()))).commit();

						TDStockLog.d(TAG, " item click works and ready to forward to currentStock page !");
						// BMP Mode  by ouyangzhihui 2011-10-13
						Class<? extends ActivityGroup_Framework>_cls = CurrentStockInfoActivity.class;
						if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
						{
							_cls = BMPCurrentStockInfoActivity.class;
						}
						
						Intent intent = new Intent(getApplicationContext(), _cls);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

						SwitchTabHostActivity(0, StockGroup.GetActivityGroupHostControl(), _cls,intent);
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
		});

		_listView.setAdapter(_twoColumnAdapter);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		updateTitle();
		_listView.invalidateViews();		
	}
	
	private void resetContent()
	{
		_twoColumnList.clear();
		_twoColumnAdapter.notifyDataSetChanged();
	}
	
	private void updateTitle()
	{
		String title = ((ITDLApplication) getApplicationContext()).getString(CommonDefn.TOP_BAR_TITLE);
		_topBarTitle.setText(title);
		if (iTypeId == 1)
		{
			_listViewHeader.setVisibility(View.VISIBLE);
		}
		else
		{
			_listViewHeader.setVisibility(View.GONE);
		}
	}
	
	private void updateData(List<String[]> result)
	{
		try
		{
			int index = 0;
			long id = START_ID + _twoColumnList.size();
			
			StringBuffer buffer = new StringBuffer();
			if (iTypeId == 6 || iTypeId == 7)
			{
				for (String[] array : result)
				{
					if (array[0] == null || array[0].length() < 1)
					{
						continue;
					}
					StockANalysisViewHolder holder = new StockANalysisViewHolder();
					holder.id = id + index;
					int length = array[0].length();
					for (int space = 0; space < StringUtils.TOTAL_LENGTH_ON_STOCKPRICE - length; space++)
					{
						buffer.append('0');
					}
					buffer.append(array[0]).append(array[1]).append(array[2]);
					holder.item_name = buffer.toString();
					buffer.setLength(0);
					holder.item_value = StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE, array[3]);
					_twoColumnList.add(holder);
					index++;
					buffer.setLength(0);
				}
	
			}
			else if (iTypeId == 0 || iTypeId == 1)
			{
				for (String[] array : result)
				{
					if (array[0] == null || array[0].length() < 1)
					{
						continue;
					}
					StockANalysisViewHolder holder = new StockANalysisViewHolder();
					holder.id = id + index;
					buffer.setLength(0);
					int length = array[0].length();
					for (int space = 0; space < StringUtils.TOTAL_LENGTH_ON_STOCKPRICE - length; space++)
					{
						buffer.append('0');
					}
					buffer.append(array[0]).append("  ").append(array[1]);
					holder.item_name = buffer.toString();
					buffer.setLength(0);

					buffer.append(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE, array[2])).append(' ').append(array[3]);
					holder.item_value = buffer.toString();
					_twoColumnList.add(holder);
					index++;
				}
			}
			else
			{
				for (String[] array : result)
				{
					if (array[0] == null || array[0].length() < 1)
					{
						continue;
					}
					StockANalysisViewHolder holder = new StockANalysisViewHolder();
					holder.id = id + index;
	
					int length = array[0].length();
					for (int space = 0; space < StringUtils.TOTAL_LENGTH_ON_STOCKPRICE - length; space++)
					{
						buffer.append('0');
					}
					buffer.append(array[0]).append("  ").append(array[1]);
					holder.item_name = buffer.toString();
					buffer.setLength(0);
	
					holder.item_value = StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE, array[2]);
					_twoColumnList.add(holder);
					index++;
					buffer.setLength(0);
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		if(_twoColumnList != null && _twoColumnList.isEmpty()) 
		{
			StockANalysisViewHolder holder = new StockANalysisViewHolder();
			holder.id = 0;
			holder.item_name  =  getResources().getString(R.string.provide_no_information);
			holder.item_value = "";
			_twoColumnList.add(holder);
		}
		
		_twoColumnAdapter.notifyDataSetChanged();
	}
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return MoreGroup.GetActivityGroupHostControl();
	}

	static public int iTypeId = 0;
	
	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		resetContent();
		return HttpAppInfo.SendAnalysisRequest(actContext, iTypeId, this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if(!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError+"("+iResult.MStatus+")");
			return;
		}
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				updateData(iResult.contentStores);
			}
		};
		_messageHandler.post(runnable);
	}
}
